package com.vehicle.admin.web.common.shiro.session;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.io.Serializable;
import java.util.Collection;

/**
 * Created by yantingbin on 2017/7/14.
 */
@Component
public class ShiroSessionDAO extends AbstractSessionDAO {

    @Autowired
    private ShiroSessionRepository shiroSessionRepository;

    @Override
    protected Serializable doCreate(Session session) {
        Assert.notNull(session, "session is null");

        Serializable sessionId = this.generateSessionId(session);

        this.assignSessionId(session, sessionId);

        shiroSessionRepository.saveSession(session);

        return sessionId;
    }

    @Override
    protected Session doReadSession(Serializable sessionId) {
        return shiroSessionRepository.getSession(sessionId);
    }

    @Override
    public void update(Session session) throws UnknownSessionException {
        shiroSessionRepository.saveSession(session);
    }

    @Override
    public void delete(Session session) {
        Assert.notNull(session, "session is null");

        Serializable id = session.getId();

        Assert.notNull(id, "sessionId is null");

        shiroSessionRepository.deleteSession(id);
    }

    @Override
    public Collection<Session> getActiveSessions() {
        return shiroSessionRepository.getAllSessions();
    }
}
